package com.brett.frame.learn.sort.base;

public class BaseSort {

	/*
	 * 交换元素
	 */
	public void exchange(int[] arr, int i, int j) {
		if (this.outflow(arr[i], arr[j]) == 1) {
			this.exchangeNeedTmp(arr, i, j);
		} else {
			this.exchangeNoTmp(arr, i, j);
		}
	}

	/**
	 * 利用临时变量存储
	 * @param arr
	 * @param i
	 * @param j
	 */
	public void exchangeNeedTmp(int[] arr, int i, int j) {
		int tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	}

	/**
	 * 不需要额外的临时变量
	 * @param arr
	 * @param i
	 * @param j
	 */
	public void exchangeNoTmp(int[] arr, int i, int j) {
		arr[i] += arr[j];
		arr[j] = arr[i] - arr[j];
		arr[i] = arr[i] - arr[j];
	}

	private int outflow(int x, int y) {
		int z = x + y;
		if (x > 0 && y > 0 && z < 0)
			return 1;
		if (x < 0 && y < 0 && z > 0)
			return 1;
		return 0;
	}
}
